package com.jwsoft.manager.core.integration.common.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.enums.AccountType;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.common.vo.operationPeriod.OperationCurVO;
import com.bifang.module.base.common.vo.operationPeriod.OperationPeriodVO;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.bifang.module.base.core.integration.OperationPeriodIntegration;
import com.bifang.module.base.core.utils.ServiceRequestUtil;
import com.bifang.module.system.common.enums.UserTypeEnum;
import com.bifang.module.system.core.dao.model.SysLoginOnline;
import com.bifang.module.system.core.dao.model.SysUser;
import com.bifang.module.system.core.dao.model.SysUserOther;
import com.bifang.module.system.core.dao.service.SysLoginOnlineService;
import com.bifang.module.system.core.dao.service.SysUserOtherService;
import com.bifang.module.system.core.dao.service.SysUserService;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.vo.common.DygxErrReturnVO;
import com.jwsoft.manager.common.vo.dygx.*;
import com.jwsoft.manager.common.vo.eduHouse.EduHouseVO;
import com.jwsoft.manager.common.vo.eduHouse.HouseInterfaceDetailVO;
import com.jwsoft.manager.common.vo.eduHouse.HouseInterfaceVO;
import com.jwsoft.manager.core.dao.model.EduHouseInterfaceData;
import com.jwsoft.manager.core.dao.model.EduSocialSecurityDetail;
import com.jwsoft.manager.core.dao.service.EduHouseInterfaceDataService;
import com.jwsoft.manager.core.integration.common.DygxIntegration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.*;

/**
 * 东阳大数据共享接口
 */
@Service
@Slf4j
public class DygxIntegrationImpl implements DygxIntegration {
    @Autowired
    CommonIntegration commonIntegration;
    @Autowired
    RedisHelper redisHelper;
    @Autowired
    OperationPeriodIntegration operationPeriodIntegration;
    @Autowired
    EduHouseInterfaceDataService eduHouseInterfaceDataService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserOtherService sysUserOtherService;
    @Autowired
    private SysLoginOnlineService sysLoginOnlineService;
    @Value("${system.config.zlb.appId}")
    private String zlbAppId;

    private final static String TOKEN="Epoint_WebSerivce_**##0601";
    private final static String searchdeptname="东阳教育局";
    private final static String searchusername="经办人员";
    private final static String areaCode="330783";

    @Override
    public String getToken() {
        return getToken(false);
    }

    @Override
    public String getToken(boolean flag) {
        String token = "";
        if (!flag) {
            if (redisHelper.hasKey(EduCache.DYGX_TOKEN)) {
                token = (String) redisHelper.get(EduCache.DYGX_TOKEN);
                if (StringUtils.isNotBlank(token)) {
                    return token;
                }
            }
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("dygx_client_id");
        commonVO.setAreaCode(areaCode);
        String clientId = commonIntegration.getValueByKeyAndArea(commonVO);
        CommonVO commonVO1 = new CommonVO();
        commonVO1.setParamKey("dygx_client_secret");
        commonVO1.setAreaCode(areaCode);
        String clientsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
        if (StringUtils.isBlank(clientId)) {
            throw new AppException("请先在系统参数表中设置dygx_client_id");
        }
        if (StringUtils.isBlank(clientsecret)) {
            throw new AppException("请先在系统参数表中设置dygx_client_secret");
        }
        CommonVO commonVO2 = new CommonVO();
        commonVO2.setParamKey("DYGX0001");
        commonVO2.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO2);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0001（获取token接口地址）");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("client_id", clientId);
        map.put("client_secret", clientsecret);
        String body = HttpUtil.get(url, map, 5000);

        if (StringUtils.isBlank(body)) {
            throw new AppException("获取token信息失败，未返回信息");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取token信息失败：" + body);
        }
        token = jsonObject.getString("access_token");
        String error = jsonObject.getString("error");
        if (StringUtils.isNotBlank(token)) {
            //东阳数据共享超时时间未300秒，系统内用260秒就换一个新的
            redisHelper.set(EduCache.DYGX_TOKEN, token, 260);
            return token;
        }
        if (StringUtils.isBlank(token) && StringUtils.isNotBlank(error)) {
            throw new AppException("获取token信息失败：" + jsonObject.getString("error"));
        } else {
            throw new AppException("获取token信息失败：未获取到token信息");
        }
    }

    @Override
    public String refreshTokenByKeyIrs(String appKey,String appsecret) {
        String refreshKey = "";
        String requestKey="";
        if(StringUtils.isBlank(appKey)){
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("ak_irs");
            commonVO.setAreaCode(areaCode);
            appKey = commonIntegration.getValueByKeyAndArea(commonVO);
            if (StringUtils.isBlank(appKey)) {
                throw new AppException("请先在系统参数表中设置ak_irs");
            }
        }
        if(StringUtils.isBlank(appsecret)) {
            CommonVO commonVO1 = new CommonVO();
            commonVO1.setParamKey("sk_irs");
            commonVO1.setAreaCode(areaCode);
            appsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
            if (StringUtils.isBlank(appsecret)) {
                throw new AppException("请先在系统参数表中设置sk_irs");
            }
        }

        CommonVO commonVO2 = new CommonVO();
        commonVO2.setParamKey("IRSGX0001");
        commonVO2.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO2);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置IRSGX0001（获取秘钥接口地址）");
        }
        Long requestTime=DateUtil.current();
        String sign= SecureUtil.md5(appKey+appsecret+requestTime).toLowerCase();
        Map<String, Object> map = new HashMap<>();
        map.put("appKey", appKey);
        map.put("sign",sign);
        map.put("requestTime",requestTime+"");
        String body = HttpUtil.get(url, map, 5000);

        if (StringUtils.isBlank(body)) {
            throw new AppException("获取IRS请求秘钥失败，未返回信息");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取IRS请求秘钥失败：" + body);
        }
        if (jsonObject.get("code").equals("00")) {
            JSONObject data = jsonObject.getJSONObject("datas");
            refreshKey=data.getString("refreshSecret") + "";
            String refreshSecretEndTime=data.getString("refreshSecretEndTime") + "";
            Long refreshSecretEndTimeL=Long.parseLong(refreshSecretEndTime);
            //保存刷新秘钥到redis
            long refreshTimeInterval=((refreshSecretEndTimeL-System.currentTimeMillis())/1000-1800);
            redisHelper.set(EduCache.irs_refresh_key,refreshKey,refreshTimeInterval);
            //更新请求秘钥到redis
            requestKey=data.getString("requestSecret") + "";
            String requestSecretEndTime=data.getString("requestSecretEndTime") + "";
            Long requestSecretEndTimeL=Long.parseLong(requestSecretEndTime);
            //保存刷新秘钥到redis
            long requestTimeInterval=(requestSecretEndTimeL-System.currentTimeMillis())/1000;
            redisHelper.set(EduCache.irs_request_key,requestKey,600);
        }
        return requestKey;
    }

    @Override
    public String refreshTokenBySecIrs(String appKey,String appsecret,String refreshKey) {
        String requestKey="";
        if(StringUtils.isBlank(appKey)) {
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("ak_irs");
            commonVO.setAreaCode(areaCode);
            appKey = commonIntegration.getValueByKeyAndArea(commonVO);
            if (StringUtils.isBlank(appKey)) {
                throw new AppException("请先在系统参数表中设置ak_irs");
            }
        }
        if(StringUtils.isBlank(appsecret)) {
            CommonVO commonVO1 = new CommonVO();
            commonVO1.setParamKey("sk_irs");
            commonVO1.setAreaCode(areaCode);
            appsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
            if (StringUtils.isBlank(appsecret)) {
                throw new AppException("请先在系统参数表中设置sk_irs");
            }
        }
        CommonVO commonVO2 = new CommonVO();
        commonVO2.setParamKey("IRSGX0002");
        commonVO2.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO2);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置IRSGX0002（刷新秘钥接口地址）");
        }
        Long requestTime=DateUtil.current();
        String sign= SecureUtil.md5(appKey+refreshKey+requestTime).toLowerCase();
        Map<String, Object> map = new HashMap<>();
        map.put("appKey", appKey);
        map.put("sign",sign);
        map.put("requestTime",requestTime+"");
        String body = HttpUtil.get(url, map, 5000);

        if (StringUtils.isBlank(body)) {
            throw new AppException("刷新IRS请求秘钥失败，未返回信息");
        }
        JSONObject requestSecretJson = null;
        try {
            requestSecretJson = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("刷新IRS请求秘钥失败：" + body);
        }
        String code = requestSecretJson.get("code").toString();
        if (code.equals("00")) {
            JSONObject data = requestSecretJson.getJSONObject("datas");
            requestKey=data.getString("requestSecret") + "";
            String requestSecretEndTime=data.getString("requestSecretEndTime") + "";
            Long requestSecretEndTimeL=Long.parseLong(requestSecretEndTime);
            //保存刷新秘钥到redis
            long requestTimeInterval=(requestSecretEndTimeL-System.currentTimeMillis())/1000;
            redisHelper.set(EduCache.irs_request_key,requestKey,600);
            //更新请求秘钥到redis
            refreshKey=data.getString("refreshSecret") + "";
            String refreshSecretEndTime=data.getString("refreshSecretEndTime") + "";
            Long refreshSecretEndTimeL=Long.parseLong(refreshSecretEndTime);
            long refreshTimeInterval=((refreshSecretEndTimeL-System.currentTimeMillis())/1000-1800);
            if(refreshTimeInterval>0){
                redisHelper.set(EduCache.irs_refresh_key,refreshKey,refreshTimeInterval);
            }else{
                redisHelper.del(EduCache.irs_refresh_key);
            }
        }else if(code.equals("03")){
            return refreshTokenByKeyIrs(appKey,appsecret);
        }else if(code.equals("02")){
            redisHelper.del(EduCache.irs_refresh_key);
            redisHelper.del(EduCache.irs_request_key);
        }
        return requestKey;
    }

    @Override
    public Map<String, Object> setIrsParams(Map<String, Object> paramsMap) {
        if (paramsMap==null){
            paramsMap =new HashMap<>();
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("ak_irs");
        commonVO.setAreaCode(areaCode);
        String appKey = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(appKey)) {
            throw new AppException("请先在系统参数表中设置ak_irs");
        }
        CommonVO commonVO1 = new CommonVO();
        commonVO1.setParamKey("sk_irs");
        commonVO1.setAreaCode(areaCode);
        String appsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
        if (StringUtils.isBlank(appsecret)) {
            throw new AppException("请先在系统参数表中设置sk_irs");
        }
        String requestKey="";
        if (redisHelper.hasKey(EduCache.irs_request_key)){
            requestKey = (String) redisHelper.get(EduCache.irs_request_key);
        }
        String refreshKey="";
        //请求秘钥过期，重新获取请求秘钥
        if(StringUtils.isBlank(requestKey)) {
            if (redisHelper.hasKey(EduCache.irs_refresh_key)){
                refreshKey = (String) redisHelper.get(EduCache.irs_refresh_key);
            }
            if (StringUtils.isBlank(refreshKey)) {
                requestKey = refreshTokenByKeyIrs(appKey, appsecret);
            } else {
                //刷新秘钥未过期，根据刷新秘钥获取请求秘钥（获取请求秘钥也会返回刷新秘钥）
                requestKey = refreshTokenBySecIrs(appKey,appsecret, refreshKey);
            }
        }
        if (StringUtils.isBlank(requestKey)){
            throw new AppException("未获取到市共享平台请求key");
        }
        String requestApiTime=System.currentTimeMillis()+"";
        String requestApiSign=SecureUtil.md5(appKey+requestKey+requestApiTime).toLowerCase();
        paramsMap.put("appKey",appKey);
        paramsMap.put("requestTime",requestApiTime);
        paramsMap.put("sign",requestApiSign);
        paramsMap.put("additional", new HashMap<>());
        return paramsMap;
    }
    @Override
    public String refreshTokenByKeyJh(String appKey, String appsecret) {
        String refreshKey = "";
        String requestKey="";
        if(StringUtils.isBlank(appKey)){
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("jhgx_client_id");
            commonVO.setAreaCode(areaCode);
            appKey = commonIntegration.getValueByKeyAndArea(commonVO);
            if (StringUtils.isBlank(appKey)) {
                throw new AppException("请先在系统参数表中设置jhgx_client_id");
            }
        }
        if(StringUtils.isBlank(appsecret)) {
            CommonVO commonVO1 = new CommonVO();
            commonVO1.setParamKey("jhgx_client_secret");
            commonVO1.setAreaCode(areaCode);
            appsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
            if (StringUtils.isBlank(appsecret)) {
                throw new AppException("请先在系统参数表中设置jhgx_client_secret");
            }
        }

        CommonVO commonVO2 = new CommonVO();
        commonVO2.setParamKey("JHGX0001");
        commonVO2.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO2);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置JhGX0001（获取秘钥接口地址）");
        }
        Long requestTime= DateUtil.current();
        String sign= SecureUtil.md5(appKey+appsecret+requestTime).toLowerCase();
        Map<String, Object> map = new HashMap<>();
        map.put("appKey", appKey);
        map.put("sign",sign);
        map.put("requestTime",requestTime+"");
        String body = HttpUtil.get(url, map, 5000);
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取金华共享请求秘钥失败，未返回信息");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取金华共享请求秘钥失败：" + body);
        }
        if (jsonObject.get("code").equals("00")) {
            JSONObject data = jsonObject.getJSONObject("datas");
            refreshKey=data.getString("refreshSecret") + "";
            String refreshSecretEndTime=data.getString("refreshSecretEndTime") + "";
            Long refreshSecretEndTimeL=null;
            try {
                Date date = DateUtil.parseDate(refreshSecretEndTime);
                refreshSecretEndTimeL=date.getTime();
            }catch (Exception e){
                refreshSecretEndTimeL=Long.parseLong(refreshSecretEndTime);
            }
            //保存刷新秘钥到redis
            long refreshTimeInterval=((refreshSecretEndTimeL-System.currentTimeMillis())/1000-1800);
            redisHelper.set(EduCache.jh_irs_refresh_key,refreshKey,refreshTimeInterval);
            //更新请求秘钥到redis
            requestKey=data.getString("requestSecret") + "";
            String requestSecretEndTime=data.getString("requestSecretEndTime") + "";
            Long requestSecretEndTimeL=null;
            try {
                Date date = DateUtil.parseDate(requestSecretEndTime);
                requestSecretEndTimeL=date.getTime();
            }catch (Exception e){
                requestSecretEndTimeL=Long.parseLong(refreshSecretEndTime);
            }
            //保存刷新秘钥到redis
            long requestTimeInterval=(requestSecretEndTimeL-System.currentTimeMillis())/1000;
            redisHelper.set(EduCache.jh_irs_request_key,requestKey,600);
        }else if(jsonObject.get("code").equals("03")){
            return refreshTokenByKeyJh(appKey,appsecret);
        }else if(jsonObject.get("code").equals("02")){
            redisHelper.del(EduCache.jh_irs_refresh_key);
            redisHelper.del(EduCache.jh_irs_request_key);
        }
        return requestKey;
    }

    @Override
    public String refreshTokenBySecJh(String appKey, String appsecret, String refreshKey) {
        String requestKey="";
        if(StringUtils.isBlank(appKey)) {
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("jhgx_client_id");
            commonVO.setAreaCode(areaCode);
            appKey = commonIntegration.getValueByKeyAndArea(commonVO);
            if (StringUtils.isBlank(appKey)) {
                throw new AppException("请先在系统参数表中设置jhgx_client_id");
            }
        }
        if(StringUtils.isBlank(appsecret)) {
            CommonVO commonVO1 = new CommonVO();
            commonVO1.setParamKey("jhgx_client_secret");
            commonVO1.setAreaCode(areaCode);
            appsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
            if (StringUtils.isBlank(appsecret)) {
                throw new AppException("请先在系统参数表中设置jhgx_client_secret");
            }
        }
        CommonVO commonVO2 = new CommonVO();
        commonVO2.setParamKey("JHGX0002");
        commonVO2.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO2);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置JHGX0002（刷新秘钥接口地址）");
        }
        Long requestTime=DateUtil.current();
        String sign= SecureUtil.md5(appKey+refreshKey+requestTime).toLowerCase();
        Map<String, Object> map = new HashMap<>();
        map.put("appKey", appKey);
        map.put("sign",sign);
        map.put("requestTime",requestTime+"");
        String body = HttpUtil.get(url, map, 5000);
        if (StringUtils.isBlank(body)) {
            throw new AppException("刷新金华共享请求秘钥失败，未返回信息");
        }
        JSONObject requestSecretJson = null;
        try {
            requestSecretJson = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("刷新金华共享请求秘钥失败：" + body);
        }
        String code = requestSecretJson.get("code").toString();
        if (code.equals("00")) {
            JSONObject data = requestSecretJson.getJSONObject("datas");
            requestKey=data.getString("requestSecret") + "";
            String requestSecretEndTime=data.getString("requestSecretEndTime") + "";
            Long requestSecretEndTimeL=null;
            try {
                Date date = DateUtil.parseDate(requestSecretEndTime);
                requestSecretEndTimeL=date.getTime();
            }catch (Exception e){
                requestSecretEndTimeL=Long.parseLong(requestSecretEndTime);
            }
            //保存刷新秘钥到redis
            long requestTimeInterval=(requestSecretEndTimeL-System.currentTimeMillis())/1000;
            redisHelper.set(EduCache.jh_irs_request_key,requestKey,600);
            //更新请求秘钥到redis
            refreshKey=data.getString("refreshSecret") + "";
            String refreshSecretEndTime=data.getString("refreshSecretEndTime") + "";
            Long refreshSecretEndTimeL=null;
            try {
                Date date = DateUtil.parseDate(refreshSecretEndTime);
                refreshSecretEndTimeL=date.getTime();
            }catch (Exception e){
                refreshSecretEndTimeL=Long.parseLong(refreshSecretEndTime);
            }
            long refreshTimeInterval=((refreshSecretEndTimeL-System.currentTimeMillis())/1000-1800);
            if(refreshTimeInterval>0){
                redisHelper.set(EduCache.jh_irs_refresh_key,refreshKey,refreshTimeInterval);
            }else{
                redisHelper.del(EduCache.jh_irs_refresh_key);
            }
        }else if(code.equals("03")){
            return refreshTokenByKeyJh(appKey,appsecret);
        }else if(code.equals("02")){
            redisHelper.del(EduCache.jh_irs_refresh_key);
            redisHelper.del(EduCache.jh_irs_request_key);
        }
        return requestKey;
    }

    @Override
    public Map<String, Object> setJhParams(Map<String, Object> paramsMap) {
        if (paramsMap==null){
            paramsMap =new HashMap<>();
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("jhgx_client_id");
        commonVO.setAreaCode(areaCode);
        String appKey = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(appKey)) {
            throw new AppException("请先在系统参数表中设置jhgx_client_id");
        }
        CommonVO commonVO1 = new CommonVO();
        commonVO1.setParamKey("jhgx_client_secret");
        commonVO1.setAreaCode(areaCode);
        String appsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
        if (StringUtils.isBlank(appsecret)) {
            throw new AppException("请先在系统参数表中设置jhgx_client_secret");
        }
        String requestKey="";
        if (redisHelper.hasKey(EduCache.jh_irs_request_key)){
            requestKey = (String) redisHelper.get(EduCache.jh_irs_request_key);
        }
        String refreshKey="";
        //请求秘钥过期，重新获取请求秘钥
        if(StringUtils.isBlank(requestKey)) {
            if (redisHelper.hasKey(EduCache.jh_irs_refresh_key)){
                refreshKey = (String) redisHelper.get(EduCache.jh_irs_refresh_key);
            }
            if (StringUtils.isBlank(refreshKey)) {
                requestKey = refreshTokenByKeyJh(appKey, appsecret);
            } else {
                //刷新秘钥未过期，根据刷新秘钥获取请求秘钥（获取请求秘钥也会返回刷新秘钥）
                requestKey = refreshTokenBySecJh(appKey,appsecret, refreshKey);
            }
        }
        if (StringUtils.isBlank(requestKey)){
            throw new AppException("未获取到市共享平台请求key");
        }
        String requestApiTime=System.currentTimeMillis()+"";
        String requestApiSign=SecureUtil.md5(appKey+requestKey+requestApiTime).toLowerCase();
        paramsMap.put("appKey",appKey);
        paramsMap.put("requestTime",requestApiTime);
        paramsMap.put("sign",requestApiSign);
        return paramsMap;
    }
    @Override
    public Map<String, String> setHeaders(String userId,String idcard,String ip,Map<String, Object> paramsMap) {

        Map<String, String>  headers=new HashMap<>();
        if (!CollectionUtils.isEmpty(paramsMap)){
            if (paramsMap.get("appKey")!=null) {
                headers.put("appKey", paramsMap.get("appKey").toString());
            }
            if (paramsMap.get("requestTime")!=null) {
                headers.put("requestTime", paramsMap.get("requestTime").toString());
            }
            if (paramsMap.get("sign")!=null) {
                headers.put("sign", paramsMap.get("sign").toString());
            }
        }
        List<String> userIds=new ArrayList<>();
        if (StringUtils.isBlank(userId)&&StringUtils.isNotBlank(idcard)) {
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(SysUser::getUserId).eq(StringUtils.isNotBlank(userId), SysUser::getUserId, userId)
                    .eq(StringUtils.isNotBlank(idcard), SysUser::getUserType, UserTypeEnum.USER.getType())
                    .eq(StringUtils.isNotBlank(idcard), SysUser::getIdcard, CommonSecureUtil.aesEncrypt(idcard));
            List<SysUser> sysUsers=sysUserService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(sysUsers)){
                for (SysUser sysUser:sysUsers){
                    userIds.add(sysUser.getUserId());
                }
            }
        }
        if (StringUtils.isNotBlank(userId)){
            userIds.add(userId);
        }
        if (StringUtils.isNotBlank(userId)&&StringUtils.isBlank(ip)){
            //ip为空，获取登录记录里面的ip
            //只查询最新一条数据
            QueryWrapper<SysLoginOnline> loginOnlineQueryWrapper=new QueryWrapper<>();
            loginOnlineQueryWrapper.lambda().select(SysLoginOnline::getLoginId).eq(SysLoginOnline::getUserId,userId).orderByDesc(SysLoginOnline::getLoginTime)
                    .last("limit 1");
            List<SysLoginOnline> sysLoginOnlines=sysLoginOnlineService.list(loginOnlineQueryWrapper);
            if (!CollectionUtils.isEmpty(sysLoginOnlines)){
                ip=sysLoginOnlines.get(0).getLoginIp();
            }
        }
        if (StringUtils.isBlank(ip)){
            try {
                ip= ServiceRequestUtil.getLocalIP();
            } catch (UnknownHostException e) {
                log.error("获取ip失败",e);
            } catch (SocketException e) {
                log.error("获取ip失败",e);
            }
        }
        if (!CollectionUtils.isEmpty(userIds)) {
            QueryWrapper<SysUserOther> otherQueryWrapper = new QueryWrapper<>();
            otherQueryWrapper.lambda().select(SysUserOther::getUserId, SysUserOther::getOpenId)
                    .in(SysUserOther::getUserId, userIds).isNotNull(SysUserOther::getOpenId)
                    .eq(SysUserOther::getLoginType, AccountType.ZLB.getKey()).orderByDesc(SysUserOther::getSysId);
            List<SysUserOther> userOthers = sysUserOtherService.list(otherQueryWrapper);
            headers.put("X-SECURITY-CHECK-TYPE", "ZLB");
            if (!CollectionUtils.isEmpty(userOthers)) {
                headers.put("X-SECURITY-USER-ID", userOthers.get(0).getOpenId());
                headers.put("X-SECURITY-CHECK-TYPE", "ZLB");
            } else {
                CommonVO commonVO = new CommonVO();
                commonVO.setParamKey("zdd_userId");
                commonVO.setAreaCode(areaCode);
                String zddUserIdStr = commonIntegration.getValueByKeyAndArea(commonVO);
                List<String> zddidList = new ArrayList<>();
                if (StringUtils.isNotBlank(zddUserIdStr)) {
                    zddidList = Arrays.asList(zddUserIdStr.split(","));
                }
                if (!CollectionUtils.isEmpty(zddidList)) {
                    //随机取zddid
                    int index = (int) (Math.random() * zddidList.size());
                    headers.put("X-SECURITY-USER-ID", zddidList.get(index));
                    headers.put("X-SECURITY-CHECK-TYPE", "ZZD");
                } else {
                    headers.put("X-SECURITY-USER-ID", zlbAppId);
                }

            }
        }else{
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("zdd_userId");
            commonVO.setAreaCode(areaCode);
            String zddUserIdStr = commonIntegration.getValueByKeyAndArea(commonVO);
            List<String> zddidList = new ArrayList<>();
            if (StringUtils.isNotBlank(zddUserIdStr)) {
                zddidList = Arrays.asList(zddUserIdStr.split(","));
            }
            if (!CollectionUtils.isEmpty(zddidList)) {
                //随机取zddid
                int index = (int) (Math.random() * zddidList.size());
                headers.put("X-SECURITY-USER-ID", zddidList.get(index));
                headers.put("X-SECURITY-CHECK-TYPE", "ZZD");
            } else {
                headers.put("X-SECURITY-CHECK-TYPE", "ZLB");
                headers.put("X-SECURITY-USER-ID", zlbAppId);
            }
        }

        headers.put("X-SECURITY-UESR-IP",ip);
        headers.put("X-SECURITY-SERVICE-ID",zlbAppId);
        return headers;
    }
    @Override
    public JSONArray getStudentStatus(String zjbh) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0002");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0002（中小学学籍信息接口地址）");
        }
        Map<String, Object> map = getDydsjParams();
        map.put("zjbh", zjbh);
        String body = HttpUtil.get(url, map, 5000);
        if (StringUtils.isBlank(body)) {
            throw new AppException("中小学学籍信息信息失败，未返回信息");
        }
        try {
            JSONArray jsonArray = JSONArray.parseArray(body);
            return jsonArray;
        } catch (Exception e) {
            DygxErrReturnVO vo =null;
            try {
                vo=(DygxErrReturnVO) JSON.parse(body);
            }catch (Exception e1){
                throw new AppException("获取中小学学籍信息信息失败：" + body);
            }
            if(vo==null){
                throw e;
            }
            throw new AppException(vo.getCode()+vo.getMessage());
        }
    }

    /**
     * 东阳市不动产登记系统提供查询服务(根据姓名身份证查询)
     *
     * @param name 姓名
     * @param zjh  证件号码
     **/
    @Override
    public JSONArray getPersonHouse(String name, String zjh,String ip) {
        if (StringUtils.isBlank(name) || StringUtils.isBlank(zjh)) {
            return new JSONArray();
        }
        if(!IdcardUtil.isValidCard(zjh)){
            //不动产不查身份证以外的数据
            return new JSONArray();
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0003");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0003（东阳市不动产登记系统提供查询服务(根据姓名身份证查询)接口地址）");
        }
        CommonVO commonVO2 = new CommonVO();
        commonVO2.setParamKey("dygx_client_id");
        commonVO2.setAreaCode(areaCode);
        String clientId = commonIntegration.getValueByKeyAndArea(commonVO2);
        if (StringUtils.isBlank(clientId)) {
            throw new AppException("请先在系统参数表中设置dygx_client_id");
        }
        String token = getToken();
        url = url + "?client_id=" + clientId + "&access_token=" + token + "&name=" + name + "&zjh=" + zjh;
        Map<String, String> headers = setHeaders(null,zjh,ip,new HashMap<>());
        String body =HttpUtil.createPost(url).addHeaders(headers).body("").timeout(6000).execute().body();
        //String body = HttpUtil.post(url, "", 5000);
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取房产信息失败，未返回信息");
        }
        if (StringUtils.isBlank(body.trim())) {
            throw new AppException("获取房产信息失败，未返回信息");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {

            throw new AppException("获取房产信息失败：" + body);

        }
        String code = jsonObject.getString("code");
        if ("0".equals(code)) {
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
            int year = 0;
            OperationCurVO curVO = new OperationCurVO();
            curVO.setOperating("XN");
            OperationPeriodVO operationPeriodVO = operationPeriodIntegration.getCurrentByOperating(curVO);
            if (operationPeriodVO != null) {
                year = operationPeriodVO.getPeriodYear();
            } else {
                year = DateUtil.thisYear();
            }
            QueryWrapper<EduHouseInterfaceData> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(EduHouseInterfaceData::getYear, year)
                    .eq(EduHouseInterfaceData::getIdcard, zjh).orderByAsc(EduHouseInterfaceData::getUpdateTime);
            List<EduHouseInterfaceData> oldList = eduHouseInterfaceDataService.list(queryWrapper);
            EduHouseInterfaceData eduHouseInterfaceData = null;
            if (CollectionUtils.isEmpty(oldList)) {
                eduHouseInterfaceData = new EduHouseInterfaceData();
                eduHouseInterfaceData.setHouseInterfaceDataId(IdUtil.simpleUUID());
                eduHouseInterfaceData.setYear(year);
                eduHouseInterfaceData.setIdcard(zjh);
                eduHouseInterfaceData.setData(JSON.toJSONString(jsonArray));
                eduHouseInterfaceDataService.save(eduHouseInterfaceData);
            } else {
                eduHouseInterfaceData = Convert.convert(EduHouseInterfaceData.class, oldList.get(0));
                eduHouseInterfaceData.setData(JSON.toJSONString(jsonArray));
                eduHouseInterfaceDataService.updateById(eduHouseInterfaceData);
            }

            return jsonArray;
        } else {
            String msg = jsonObject.getString("message");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("msg");
            }
            throw new AppException(code + msg);
        }


    }

    /***
     * 住建局房地产网签数据
     * @param zjhm 证件号码
     * **/
    @Override
    public List<WqVO> getHouseOnline(String zjhm) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0004");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0004（住建局房地产网签数据接口地址）");
        }
        Map<String, Object> map = getDydsjParams();
        map.put("zjhm", zjhm);
        String body = HttpUtil.get(url, map, 5000);
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取住建局房地产网签数据信息失败，未返回信息");
        }
        try {
            List<WqVO> list= JSONArray.parseArray(body, WqVO.class);
            return list;
        } catch (Exception e) {
            DygxErrReturnVO vo =null;
            try {
                vo=(DygxErrReturnVO) JSON.parse(body);
            }catch (Exception e1){
                throw new AppException("获取住建局房地产网签数据信息失败：" + body);
            }
            if(vo==null){
                throw e;
            }
            throw new AppException(vo.getCode()+vo.getMessage());
        }
    }

    /**
     * 个人参保查询（东阳）
     * @param aac147 证件号码
     * **/
    @Override
    public List<CbVO> getGrcbDy(String aac147,String ip) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0006");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0006（个人参保查询接口地址）");
        }
        Map<String, Object> map = getDydsjParams();
        map.put("aac147", aac147);
        Map<String, String> headers = setHeaders(null,aac147,ip,map);

        String body =HttpUtil.createGet(url).addHeaders(headers).form(map).timeout(6000).execute().body();

        if (StringUtils.isBlank(body)) {
            throw new AppException("获取个人参保信息失败，未返回信息");
        }
        try {
            List<CbVO> list= JSONArray.parseArray(body, CbVO.class);
            return list;
        } catch (Exception e) {
            DygxErrReturnVO vo =null;
            try {
                vo = (DygxErrReturnVO) JSON.parse(body);

            }catch (Exception e1){
                throw new AppException("获取个人参保信息失败：" + body);
            }
            if(vo==null){
                throw e;
            }
            throw new AppException(vo.getCode()+vo.getMessage());
        }
    }

    @Override
    public JSONArray getGrcb(String aac002, String aac003,String ip) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0009");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKey(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0009（个人参保查询（省）接口地址）");
        }
        CommonVO commonVO2 = new CommonVO();
        commonVO2.setParamKey("dygx_client_id");
        commonVO2.setAreaCode(areaCode);
        String clientId = commonIntegration.getValueByKey(commonVO2);
        if (StringUtils.isBlank(clientId)) {
            throw new AppException("请先在系统参数表中设置dygx_client_id");
        }
        String token = getToken();
        Map<String, Object> map = new HashMap<>();
        map.put("aac002", aac002);
        map.put("aac003", aac003);
        setSdsjParams(map);
        url=url+"?client_id="+clientId+"&access_token="+token;
        Map<String, String> headers = setHeaders(null,aac002,ip,map);

        String body =HttpUtil.createPost(url).addHeaders(headers).form(map).timeout(6000).execute().body();
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取省个人参保信息失败，未返回信息");
        }
        JSONObject jsonObject =null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取省个人参保信息失败：" + body);
        }
        String code=jsonObject.getString("code");
        if("00".equals(code)){
            JSONObject datas = jsonObject.getJSONObject("datas");
            String result=datas.getString("result");
            if("00".equals(result)){
                JSONArray jsonArray = datas.getJSONArray("datas");
                return jsonArray;
            }else{
                String resultmsg=jsonObject.getString("resultmsg");
                throw new AppException("省大数据平台接口返回：错误码："+result+"错误描述："+resultmsg);
            }
        }else{
            String msg=jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)){
                msg=jsonObject.getString("message");
            }
            throw new AppException("东阳大数据平台接口返回：错误码："+code+"错误描述："+msg);
        }
    }

    @Override
    public JSONArray getOrgInfo(String uniscid) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0007");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKey(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0007（市场监督管理局市场主体信息接口地址）");
        }
        Map<String, Object> map =getDydsjParams();
        map.put("uniscid", uniscid);
        String body = HttpUtil.get(url, map, 10000);
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取市场监督管理局市场主体信息失败，未返回信息");
        }
        try {
            JSONArray jsonArray = JSONArray.parseArray(body);
            return jsonArray;
        } catch (Exception e) {
            DygxErrReturnVO vo =null;
            try {
                vo = (DygxErrReturnVO) JSON.parse(body);
            }catch (Exception e1){
                throw new AppException("获取市场监督管理局市场主体信息失败：" + body);
            }
            if(vo==null){
                throw e;
            }
            throw new AppException(vo.getCode()+vo.getMessage());
        }
    }

    /**
     * 省公安厅居民户口簿(家庭) 作废
     *
     * @param czrkgmsfhm 身份证号码
     **/
    @Override
    public JSONArray getFamilyInfo(String czrkgmsfhm) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0005");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0005（省公安厅居民户口簿(家庭)接口地址）");
        }
        CommonVO commonVO1 = new CommonVO();
        commonVO1.setAreaCode(areaCode);
        commonVO1.setParamKey("dygx_client_id");
        String clientId = commonIntegration.getValueByKeyAndArea(commonVO1);
        if (StringUtils.isBlank(clientId)) {
            throw new AppException("请先在系统参数表中设置dygx_client_id");
        }
        String token = getToken();
        Map<String, Object> map = new HashMap<>();
        map.put("czrkgmsfhm", czrkgmsfhm);
        map.put("additional", new HashMap<>());
        url = url + "?client_id=" + clientId + "&access_token=" + token;
        String body = HttpUtil.post(url, map, 10000);
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取省公安厅居民户口簿(家庭)信息失败，未返回信息");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取省公安厅居民户口簿(家庭)信息失败：" + body);
        }
        String code = jsonObject.getString("code");
        if ("00".equals(code)) {
            JSONArray jsonArray = jsonObject.getJSONArray("datas");
            return jsonArray;
        } else {
            String msg = jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("message");
            }
            throw new AppException("东阳大数据平台接口返回：错误码：" + code + "错误描述：" + msg);
        }
    }
    /**
     * 省公安厅居民户口簿(家庭) irs
     *
     * @param czrkgmsfhm 身份证号码
     **/
    @Override
    public JSONArray getFamilyInfoIrs(String czrkgmsfhm,String ip) {

        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("IRSGX0003");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置IRSGX0003（省公安厅居民户口簿(家庭)Irs接口地址）");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("czrkgmsfhm", czrkgmsfhm);
        map.put("User_ID", czrkgmsfhm);
        map.put("Organization_Id", "330783");
        map.put("Organization", "东阳市教育局");
        setIrsParams(map);
        Map<String, String> headers = setHeaders(null,czrkgmsfhm,ip,map);
        String body =HttpUtil.createGet(url).addHeaders(headers).form(map).timeout(6000).execute().body();
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取省公安厅居民户口簿(家庭)信息失败，未返回信息");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取省公安厅居民户口簿(家庭)信息失败：" + body);
        }
        String code = jsonObject.getString("code");
        if ("00".equals(code)) {
            JSONArray jsonArray = jsonObject.getJSONArray("datas");
            return jsonArray;
        } else {
            String msg = jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("message");
            }
            throw new AppException("IRS平台接口返回：错误码：" + code + "错误描述：" + msg);
        }
    }


    @Override
    public List<DyHouseholdVO> getDyHjInfo(String gmsfhm,String ip) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0010");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0010（户籍信息（东阳）接口地址）");
        }

        Map<String, Object> map = getDydsjParams();
        map.put("GMSFHM", gmsfhm);
        Map<String, String> headers = setHeaders(null,gmsfhm,ip,map);
        String body = HttpUtil.createGet(url).addHeaders(headers).form(map).timeout(6000).execute().body();
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取市户籍信息（东阳）失败，未返回信息");
        }
        try {
            List<DyHouseholdVO> list= JSONArray.parseArray(body, DyHouseholdVO.class);
            if(!CollectionUtils.isEmpty(list)){
                for(DyHouseholdVO dyHouseholdVO:list){
                    // 完整地址处理  目前数据 mlxz 或者mlph 是全部地址
                    String address="";
                    /***
                    if(SpecialStringUtils.isNotBlank(dyHouseholdVO.getHkszdxs())){
                        address=address+dyHouseholdVO.getHkszdxs();
                    }
                    if(SpecialStringUtils.isNotBlank(dyHouseholdVO.getHkszxzjd())){
                        address=address+dyHouseholdVO.getHkszxzjd();
                    }
                    if(SpecialStringUtils.isNotBlank(dyHouseholdVO.getHkszdjlx())){
                        address=address+dyHouseholdVO.getHkszdjlx();
                    }
                    ***/
                    if(StringUtils.isNotBlank(dyHouseholdVO.getMlph())){
                        address=address+dyHouseholdVO.getMlph();
                    }else{
                        if(StringUtils.isNotBlank(dyHouseholdVO.getMlxz())){
                            address=address+dyHouseholdVO.getMlxz();
                        }
                    }
                    //全角转半角
                    //address = Convert.toDBC(address);
                    dyHouseholdVO.setHkAdreess(address);
                }
            }
            return list;
        } catch (Exception e) {
            DygxErrReturnVO vo=null;
            try {
                vo = (DygxErrReturnVO) JSON.parse(body);
            }catch (Exception e1){
                throw new AppException("获取户籍信息（东阳）失败：" + body);
            }
            if(vo==null){
                throw e;
            }
            throw new AppException(vo.getCode()+vo.getMessage());
        }

    }

    @Override
    public List<DyJzzVO> getDyJzz(String sfzh,String ip) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0011");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0011（居住证信息（东阳）接口地址）");
        }

        Map<String, Object> map = getDydsjParams();
        map.put("sfzh", sfzh);
        Map<String, String> headers = setHeaders(null,sfzh,ip,map);
        String body = HttpUtil.createGet(url).addHeaders(headers).form(map).timeout(6000).execute().body();

        if (StringUtils.isBlank(body)) {
            throw new AppException("获取市居住证信息（东阳）失败，未返回信息");
        }
        try {
            List<DyJzzVO> list= JSONArray.parseArray(body, DyJzzVO.class);
            return list;
        } catch (Exception e) {
            DygxErrReturnVO vo =null;
            try {
                vo = (DygxErrReturnVO) JSON.parse(body);
            }catch (Exception e1){
                throw new AppException("获取居住证信息（东阳）失败：" + body);
            }
            if(vo==null){
                throw e;
            }
            throw new AppException(vo.getCode()+vo.getMessage());
        }
    }

    @Override
    public JSONArray getJzzIrs(String sfzh, String xm, String ip) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("IRSGX0005");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置IRSGX0005（省公安厅居住证Irs接口地址）");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sfzh", sfzh);
        map.put("xm", xm);
        map.put("User_ID", sfzh);
        map.put("User_Name", xm);
        map.put("Organization_Id", "330783");
        map.put("Organization", "东阳市教育局");
        setIrsParams(map);
        Map<String, String> headers = setHeaders(null,sfzh,ip,map);
        String body =HttpUtil.createGet(url).addHeaders(headers).form(map).timeout(15000).execute().body();

        if (StringUtils.isBlank(body)) {
            throw new AppException("获取省公安厅居住证信息失败，未返回信息");
        }
        System.out.println("居住证："+body);
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取省公安厅居住证信息失败：" + body);
        }
        String code = jsonObject.getString("code");
        if ("00".equals(code)) {
            JSONArray jsonArray = jsonObject.getJSONArray("datas");
            return jsonArray;
        } else {
            String msg = jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("message");
            }
            throw new AppException("IRS平台接口返回：错误码：" + code + "错误描述：" + msg);
        }
    }

    @Override
    public List<CszmVO> getCszm(CszmQueryVO cszmQueryVO) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0012");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0012（出生证明（省）接口地址）");
        }
        CommonVO commonVO1 = new CommonVO();
        commonVO1.setParamKey("dygx_client_id");
        commonVO1.setAreaCode(areaCode);
        String clientId = commonIntegration.getValueByKeyAndArea(commonVO1);
        if (StringUtils.isBlank(clientId)) {
            throw new AppException("请先在系统参数表中设置dygx_client_id");
        }
        String token = getToken();
        Map<String, Object> map = new HashMap<>();
        map.put("xm", cszmQueryVO.getXm());
        map.put("mxm", cszmQueryVO.getMxm());
        map.put("msfz", cszmQueryVO.getMsfz());
        map.put("fxm", cszmQueryVO.getFxm());
        map.put("fsfz", cszmQueryVO.getFsfz());
        setSdsjParams(map);
        url=url+"?client_id="+clientId+"&access_token="+token;
        String body = HttpUtil.post(url,map, 10000);
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取出生证明（省）信息失败，未返回信息");
        }
        JSONObject jsonObject =null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取出生证明（省）信息失败：" + body);
        }
        String code=jsonObject.getString("code");
        List<CszmVO> list=new ArrayList<>();
        if("00".equals(code)){
            JSONObject datas = jsonObject.getJSONObject("datas");
            String result=datas.getString("result");
            if("00".equals(result)){
                JSONArray jsonArray = datas.getJSONArray("datas");
                if(jsonArray.isEmpty()){
                    return list;
                }
                for (Iterator<Object> iterator = jsonArray.iterator(); iterator.hasNext(); ) {
                    JSONObject jsonObj = (JSONObject) iterator.next();
                    CszmVO cszmVO=jsonObj.getObject("struct",CszmVO.class);
                    JSONObject file=jsonObj.getJSONObject("file");
                    if(file!=null){
                        cszmVO.setName(file.getString("name"));
                        cszmVO.setUrl(file.getString("url"));
                    }
                    list.add(cszmVO);
                }
            }else{
                String resultmsg=datas.getString("resultmsg");
                throw new AppException("出生证明省大数据平台接口返回：错误码："+result+"错误描述："+resultmsg);
            }
        }else{
            String msg=jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)){
                msg=jsonObject.getString("message");
            }
            throw new AppException("出生证明东阳大数据平台接口返回：错误码："+code+"错误描述："+msg);
        }
        return list;
    }

    @Override
    public List<QyVO> getQy(QyQueryVO qyQueryVO) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0013");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0013（法人登记基本信息（省）接口地址）");
        }
        CommonVO commonVO1 = new CommonVO();
        commonVO1.setParamKey("dygx_client_id");
        commonVO1.setAreaCode(areaCode);
        String clientId = commonIntegration.getValueByKeyAndArea(commonVO1);
        if (StringUtils.isBlank(clientId)) {
            throw new AppException("请先在系统参数表中设置dygx_client_id");
        }
        String token = getToken();
        Map<String, Object> map = new HashMap<>();
        map.put("djzch", qyQueryVO.getDjzch());
        map.put("frdwmc", qyQueryVO.getFrdwmc());
        map.put("tyxydm", qyQueryVO.getTyxydm());
        map.put("zzjgdm", qyQueryVO.getZzjgdm());
        setSdsjParams(map);
        url=url+"?client_id="+clientId+"&access_token="+token;
        String body = HttpUtil.post(url,map, 10000);
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取法人登记基本信息（省）信息失败，未返回信息");
        }
        JSONObject jsonObject =null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取法人登记基本信息（省）信息失败：" + body);
        }
        String code=jsonObject.getString("code");
        List<QyVO> list=new ArrayList<>();
        if("00".equals(code)){
            JSONObject datas = jsonObject.getJSONObject("datas");
            String result=datas.getString("result");
            if("00".equals(result)){
                JSONArray jsonArray = datas.getJSONArray("datas");
                if(jsonArray.isEmpty()){
                    return list;
                }
                for (Iterator<Object> iterator = jsonArray.iterator(); iterator.hasNext(); ) {
                    JSONObject jsonObj = (JSONObject) iterator.next();
                    QyVO qyVO=jsonObj.getObject("struct",QyVO.class);
                    JSONObject file=jsonObj.getJSONObject("file");
                    if(file!=null){
                        qyVO.setName(file.getString("name"));
                        qyVO.setUrl(file.getString("url"));
                    }
                    list.add(qyVO);
                }
            }else{
                String resultmsg=datas.getString("resultmsg");
                throw new AppException("法人登记基本信息省大数据平台接口返回：错误码："+result+"错误描述："+resultmsg);
            }
        }else{
            String msg=jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)){
                msg=jsonObject.getString("message");
            }
            throw new AppException("法人登记基本信息东阳大数据平台接口返回：错误码："+code+"错误描述："+msg);
        }
        return list;
    }

    @Override
    public JSONArray getFrQyIrs(String identificationId) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("IRSGX0004");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置IRSGX0004（法人企业信息查询Irs接口地址）");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("identificationId", identificationId);
        setIrsParams(map);
        HashMap<String, String> headers = new HashMap<>();//存放请求头，可以存放多个请求头
        headers.put("X-SECURITY-USER-ID", zlbAppId);
        headers.put("X-SECURITY-CHECK-TYPE", "ZLB");
        String body =HttpUtil.createGet(url).addHeaders(headers).form(map).timeout(6000).execute().body();

        if (StringUtils.isBlank(body)) {
            throw new AppException("获取法人企业信息查询信息失败，未返回信息");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取法人企业信息查询信息失败：" + body);
        }
        String code = jsonObject.getString("code");
        if ("00".equals(code)) {
            JSONArray jsonArray = jsonObject.getJSONArray("datas");
            return jsonArray;
        } else {
            String msg = jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("message");
            }
            throw new AppException("IRS平台接口返回：错误码：" + code + "错误描述：" + msg);
        }
    }

    @Override
    public List<EduSocialSecurityDetail> getCbDetail(String aac147,String ip) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0014");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0014（获取社保近6个月缴费记录接口地址）");
        }
        Map<String, Object> map = getDydsjParams();
        map.put("zjhm", aac147);
        Map<String, String> headers = setHeaders(null,aac147,ip,map);
        String body =HttpUtil.createGet(url).addHeaders(headers).form(map).timeout(15000).execute().body();

        if (StringUtils.isBlank(body)) {
            throw new AppException("获取社保近6个月缴费记录信息失败，未返回信息");
        }
        try {
            List<EduSocialSecurityDetail> list= JSONArray.parseArray(body, EduSocialSecurityDetail.class);
            return list;
        } catch (Exception e) {
            DygxErrReturnVO vo =null;
            try {
                vo = (DygxErrReturnVO) JSON.parse(body);

            }catch (Exception e1){
                throw new AppException("获取社保近6个月缴费记录信息失败：" + body);
            }
            if(vo==null){
                throw e;
            }
            throw new AppException(vo.getCode()+vo.getMessage());
        }
    }

    @Override
    public Integer getCbJfys(String aac147,String ip) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("DYGX0015");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置DYGX0015（根据身份证提供该人员社保累计缴费月数接口地址）");
        }
        Map<String, Object> map = getDydsjParams();
        map.put("zjhm", aac147);
        Map<String, String> headers = setHeaders(null,aac147,ip,map);
        String body =HttpUtil.createGet(url).addHeaders(headers).form(map).timeout(15000).execute().body();

        if (StringUtils.isBlank(body)) {
            throw new AppException("根据身份证提供该人员社保累计缴费月数信息查询失败，未返回信息");
        }
        try {
            JSONArray jsonArray = JSONArray.parseArray(body);
            if (ObjectUtils.isEmpty(jsonArray)) {
                return 0;
            }else {
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                if(StringUtils.isNotEmpty(jsonObject.getString("ljjfys"))){
                    return Integer.parseInt(jsonObject.getString("ljjfys"));
                }else {
                    return 0;
                }

            }
        } catch (Exception e) {
            DygxErrReturnVO vo = null;
            try {
                vo = (DygxErrReturnVO) JSON.parse(body);

            } catch (Exception e1) {
                throw new AppException("根据身份证提供该人员社保累计缴费月数信息查询失败：" + body);
            }
            if (vo == null) {
                throw e;
            }
            throw new AppException(vo.getCode() + vo.getMessage());
        }
    }

    @Override
    public List<WqVO> getHouseOnlineJH2(String zjhm, String htbh, String htbah, String xzqh,String ip) {
        if (StringUtils.isBlank(htbh)){
            return new ArrayList<>();
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("JHGX0003");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置JHGX0003（通过合同编号，行政区划查询金华市二手房合同查询接口地址）");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("HTBH", htbh);
        map.put("HTBAH", htbah);
        map.put("XZQH", StringUtils.isBlank(xzqh)?areaCode:xzqh);
        Map<String,Object> additional=new HashMap<>();
        additional.put("powerMatters","许可-0000-00");
        additional.put("subPowerMatters","许可-0000-0101");
        additional.put("accesscardId",zjhm);
        map.put("additional",additional);
        setJhParams(map);
        Map<String, String> headers = setHeaders(null,null,ip,map);

        String charset="UTF-8";
        HttpResponse response = HttpUtil.createPost(url).charset(charset).addHeaders(headers).header("Content-Type", "application/x-www-form-urlencoded").form(map).timeout(6 * 1000).execute();
        String body = response.body();
        if (StringUtils.isBlank(body)) {
            throw new AppException("金华市二手房合同查询失败，未返回信息");
        }
        System.out.println(body);
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("金华市二手房合同查询失败：" + body);
        }
        String code = jsonObject.getString("code");
        if ("00".equals(code)) {
            JSONObject datas = jsonObject.getJSONObject("datas");
            String fcCode = datas.getString("code");
            if("00".equalsIgnoreCase(fcCode)){
                JSONArray jsonArray=datas.getJSONArray("datas");
                List<WqVO> wqVOS=new ArrayList<>();
                for(int i=0;i<jsonArray.size();i++){
                    WqVO wqVO=new WqVO();
                    JSONObject wq=jsonArray.getJSONObject(i);
                    wqVO.setDz(wq.getString("FWZL"));
                    wqVO.setBasj(wq.getString("HTBASJ"));
                    wqVO.setHtbabh(wq.getString("HTBAH"));
                    wqVO.setHtbh(wq.getString("HTBH"));
                    wqVO.setXm(wq.getString("SRFMC"));
                    wqVO.setIdcard(wq.getString("SRFZJHM"));
                    wqVO.setSzqx(wq.getString("SZQX"));
                    wqVO.setSzcs(wq.getString("SZCS"));
                    wqVO.setFwxz(wq.getString("FWXZ"));
                    wqVO.setFwyt(wq.getString("FWYT"));
                    wqVO.setFwtybh(wq.getString("FWTYBH"));
                    wqVO.setHtid(wq.getString("ID"));
                    wqVO.setHtqdsj(wq.getString("HTQDSJ"));
                    wqVO.setType("2");
                    wqVOS.add(wqVO);

                }
                return wqVOS;
            }else{
                throw new AppException("金华市二手房合同查询失败：code("+fcCode+")" + datas.getString("msg"));
            }

        } else {
            if(code.equals("02")){
                redisHelper.del(EduCache.jh_irs_refresh_key);
                redisHelper.del(EduCache.jh_irs_request_key);
            }
            String msg = jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("message");
            }
            throw new AppException("金华IRS平台接口返回：错误码：" + code + "错误描述：" + msg);
        }
    }

    @Override
    public List<WqVO> getHouseOnlineJH1(String zjhm, String htbh, String htbah, String xzqh,String ip) {
        if (StringUtils.isBlank(htbh)){
            return new ArrayList<>();
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("JHGX0004");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置JHGX0004（通过合同编号，行政区划查询金华市一手房合同查询接口地址）");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("HTBH", htbh);
        map.put("HTBAH", htbah);
        map.put("XZQH", StringUtils.isBlank(xzqh)?areaCode:xzqh);
        Map<String,Object> additional=new HashMap<>();
        additional.put("powerMatters","许可-0000-00");
        additional.put("subPowerMatters","许可-0000-0101");
        additional.put("accesscardId",zjhm);
        map.put("additional",additional);
        setJhParams(map);
        System.out.println(JSON.toJSONString(map));
        Map<String, String> headers = setHeaders(null,null,ip,map);
        String charset="UTF-8";
        HttpResponse response = HttpUtil.createPost(url).addHeaders(headers).charset(charset).header("Content-Type", "application/x-www-form-urlencoded").form(map).timeout(6 * 1000).execute();
        String body = response.body();
        if (StringUtils.isBlank(body)) {
            throw new AppException("金华市一手房合同查询失败，未返回信息");
        }
        System.out.println(body);
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("金华市二手房合同查询失败：" + body);
        }
        String code = jsonObject.getString("code");
        if ("00".equals(code)) {
            JSONObject datas = jsonObject.getJSONObject("datas");
            String fcCode = datas.getString("code");
            if("00".equalsIgnoreCase(fcCode)){
                JSONArray jsonArray=datas.getJSONArray("datas");
                List<WqVO> wqVOS=new ArrayList<>();
                for(int i=0;i<jsonArray.size();i++){
                    WqVO wqVO=new WqVO();
                    JSONObject wq=jsonArray.getJSONObject(i);
                    wqVO.setDz(wq.getString("FWZL"));
                    wqVO.setBasj(wq.getString("HTBASJ"));
                    wqVO.setHtbabh(wq.getString("HTBAH"));
                    wqVO.setHtbh(wq.getString("HTBH"));
                    wqVO.setXm(wq.getString("SRFMC"));
                    wqVO.setIdcard(wq.getString("SRFZJHM"));
                    wqVO.setSzqx(wq.getString("SZQX"));
                    wqVO.setSzcs(wq.getString("SZCS"));
                    wqVO.setFwxz(wq.getString("FWXZ"));
                    wqVO.setFwyt(wq.getString("FWYT"));
                    wqVO.setFwtybh(wq.getString("FWTYBH"));
                    wqVO.setHtid(wq.getString("ID"));
                    wqVO.setHtqdsj(wq.getString("HTQDSJ"));
                    wqVO.setType("1");
                    wqVOS.add(wqVO);

                }
                return wqVOS;
            }else{
                throw new AppException("金华市一手房合同查询失败：code("+fcCode+")" + datas.getString("msg"));
            }

        } else {
            if(code.equals("02")){
                redisHelper.del(EduCache.jh_irs_refresh_key);
                redisHelper.del(EduCache.jh_irs_request_key);
            }
            String msg = jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("message");
            }
            throw new AppException("金华IRS平台接口返回：错误码：" + code + "错误描述：" + msg);
        }
    }

    @Override
    public List<HouseInterfaceVO> getHouseByBdczh(String bdcqzh, String qlrmc,String ip) {
        if (StringUtils.isBlank(bdcqzh)){
            throw new AppException("不动产证号不能为空");
        }
        if (StringUtils.isBlank(qlrmc)){
            throw new AppException("权利人名称不能为空");
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("JHGX0005");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置JHGX0005（金华市房产信息验证接口地址）");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("bdcqzh", bdcqzh);
        map.put("qlrmc", qlrmc);
        Map<String,Object> additional=new HashMap<>();
        additional.put("powerMatters","许可-0000-00");
        additional.put("subPowerMatters","许可-0000-0101");
        additional.put("accesscardId","东阳新生报名");
        map.put("additional",additional);
        setJhParams(map);
        System.out.println(JSON.toJSONString(map));
        Map<String, String> headers = setHeaders(null,null,ip,map);
        String charset="UTF-8";
        HttpResponse response = HttpUtil.createPost(url).addHeaders(headers).charset(charset).header("Content-Type", "application/x-www-form-urlencoded").form(map).timeout(6 * 1000).execute();
        String body = response.body();
        if (StringUtils.isBlank(body)) {
            throw new AppException("金华市房产信息验证查询失败，未返回信息");
        }
        System.out.println(body);
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("金华市房产信息验证查询失败：" + body);
        }
        String code = jsonObject.getString("code");
        if ("00".equals(code)) {
            JSONObject datas = jsonObject.getJSONObject("datas");
            JSONObject data = datas.getJSONObject("data");
            JSONArray array = data.getJSONArray("list");
            List<HouseInterfaceVO> eduHouseVOList = new ArrayList<>();
            for(int i=0;i<array.size();i++){
                JSONObject house = array.getJSONObject(i);
                JSONArray bdclist= house.getJSONArray("bdclist");
                String address=bdclist.getJSONObject(0).getString("FWZL");
                HouseInterfaceVO eduHouseVO = new HouseInterfaceVO();
                eduHouseVO.setQxbm(house.getString("QXBH"));
                eduHouseVO.setGyqk(house.getString("GYFS"));
                eduHouseVO.setZl(address);
                eduHouseVO.setDjsj(house.getString("DJSJ"));
                List<HouseInterfaceDetailVO> qlrxxList=new ArrayList<>();
                JSONArray qlrlist= house.getJSONArray("qlrlist");
                for (int j=0;j<qlrlist.size();j++){
                    HouseInterfaceDetailVO qlrxx = new HouseInterfaceDetailVO();
                    qlrxx.setZjh(qlrlist.getJSONObject(j).getString("QLRZJH"));
                    qlrxx.setQlr(qlrlist.getJSONObject(j).getString("QLRMC"));
                    qlrxx.setZjzl(qlrlist.getJSONObject(j).getString("QLRZJLX"));
                    qlrxx.setBdcqzh(qlrlist.getJSONObject(j).getString("CQZH"));
                    qlrxxList.add(qlrxx);
                }
                eduHouseVO.setQlrxxList(qlrxxList);
                eduHouseVOList.add(eduHouseVO);
            }

            return eduHouseVOList;

        } else {
            if(code.equals("02")){
                redisHelper.del(EduCache.jh_irs_refresh_key);
                redisHelper.del(EduCache.jh_irs_request_key);
            }
            String msg = jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("message");
            }
            throw new AppException("金华IRS平台接口返回：错误码：" + code + "错误描述：" + msg);
        }
    }

    // 设置省大数据接口参数
    private void setSdsjParams(Map<String,Object> map){
        map.put("token", TOKEN);
        if(StringUtils.isNotBlank(SessionUtil.getFullName())){
            map.put("searchusername", SessionUtil.getFullName());
        }else{
            map.put("searchusername", searchusername);
        }
        map.put("searchdeptname", searchdeptname);
        map.put("additional", new HashMap<>());
    }

    // 获取东阳大数据token等参数
    private Map<String,Object> getDydsjParams(){
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("dygx_client_id");
        commonVO.setAreaCode(areaCode);
        String clientId = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(clientId)) {
            throw new AppException("请先在系统参数表中设置dygx_client_id");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("client_id", clientId);
        String token = getToken();
        map.put("access_token", token);
        return map;
    }

}
